package com.tian.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.tian.dto.ChargeUserLoginResDto;
import com.tian.dto.PayNotifyTestReqDto;
import com.tian.entity.ChargePayOrder;
import com.tian.exception.BusinessException;
import com.tian.service.PayBaseService;
import com.tian.service.PaymentService;
import com.tian.util.UserCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * {@code @description:} 支付宝支付实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-11-23 15:29
 * {@code @version:} 1.0
 */
@Slf4j
@Service("aliPaymentService")
public class AliPaymentServiceImpl extends PayBaseService implements PaymentService {

    @Resource
    private AlipayConfig alipayConfig;

    @Override
    public String prepay(ChargePayOrder chargePayOrder, String msg, Boolean isTest) {
        //获取当前登录信息
        ChargeUserLoginResDto user = UserCacheUtil.getUser();
        try {
            AlipayTradePagePayResponse response = getAlipayTradePagePayResponse(chargePayOrder.getAmount(), msg, chargePayOrder.getOrderNo());
            if (!response.isSuccess()) {
                log.error("支付宝支付接口调用失败，错误信息：{}", response.getBody());
                throw new BusinessException("支付宝支付接口调用失败，请稍后重试");
            }
            return response.getBody();
        } catch (AlipayApiException e) {
            log.error("支付宝支付接口调用失败，错误信息：{}", e.getMessage());
            throw new BusinessException("支付宝支付接口调用失败，请稍后重试");
        }
    }

    private AlipayTradePagePayResponse getAlipayTradePagePayResponse(BigDecimal amount, String msg, String orderNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        model.setOutTradeNo(orderNo);
        model.setTotalAmount(amount.toString());
        model.setSubject(msg);
        model.setQrPayMode("1");
        model.setQrcodeWidth(100L);
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        request.setBizModel(model);

        return alipayClient.pageExecute(request, "POST");
    }

    /**
     * 支付结果通知 ----- 充值
     *
     * @param request
     * @param payNotifyTestReqDto
     */
    @Override
    public ResponseEntity payNotify(HttpServletRequest request, PayNotifyTestReqDto payNotifyTestReqDto) {
        return null;
    }
}
